import WorkerPool from './WorkerPool';

class RenderWorkerManager {
    constructor() {
        this.workerPool = null;
        this.messageId = 0;
    }

    // 初始化 Worker Pool
    init() {
        if (this.workerPool) return;

        // 创建Worker池，使用硬件并发数或默认4个worker
        this.workerPool = new WorkerPool(
            new URL('../workers/renderWorker.js', import.meta.url),
            navigator.hardwareConcurrency || 4
        );
    }

    // 渲染计算
    async render(objects, canvasWidth, canvasHeight) {
        return this._postMessage('render', {
            objects,
            canvasWidth,
            canvasHeight
        });
    }

    // 布局计算
    async calculateLayout(objects, canvasWidth, canvasHeight, layoutType = 'grid') {
        return this._postMessage('layout', {
            objects,
            canvasWidth,
            canvasHeight,
            layoutType
        });
    }

    // 发送消息到 Worker Pool
    _postMessage(type, data) {
        if (!this.workerPool) {
            this.init();
        }

        const messageId = this.messageId++;

        return this.workerPool.execute({
            type,
            data,
            messageId
        });
    }

    // 终止 Worker Pool
    terminate() {
        if (this.workerPool) {
            this.workerPool.terminate();
            this.workerPool = null;
        }
    }
}

// 创建单例实例
const renderWorkerManager = new RenderWorkerManager();

export default renderWorkerManager; 